package com.crm.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.util.MultiValueMap;

public class XMLUtil {
	
	public static void main(String[] args){
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("rule1_value", "111");
		map.put("rule2_value", "111");

	}
	
	
	/**
	 * @return
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 * 
	 * 解析信息回流规则
	 */
	public static Map<String, Object> parseInquiriesRule() throws FileNotFoundException, DocumentException{
		
		SAXReader reader = new SAXReader(); 
		
		Document document = reader.read(XMLUtil.class.getResource("/inquiries-rule.xml")); 
		
		Element root = document.getRootElement();
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("rules", parseRules(root));
		map.put("options", parseCondition(root));
		map.put("operations", parseBehavior(root));
		
		return map;
		
	}
	
	
	/**
	 * @return
	 * 
	 * 解析规则
	 * 
	 */
	public static List<Map<String,String>> parseRules(Element root){
		
		Element rules = root.element("rules");

		Iterator<?> i = rules.elementIterator("rule");
		
		List<Map<String,String>> results = new ArrayList<>();
		
		while(i.hasNext()){
			Element rule = (Element)i.next();
			
			String ruleText = rule.attributeValue("name");
			
			String checked = rule.attributeValue("checked");
			String desc = rule.elementText("desc");
			
			Iterator<?> values = rule.elementIterator("value");
			
			List<String> list = new ArrayList<>();
			
			Map<String, String> map = new HashMap<>();
			
			while(values.hasNext()){
				Element value = (Element)values.next();
				String name = value.attributeValue("name");
				list.add(" <input type='text' name='"+name+"' value='"+value.getTextTrim()+"'/> ");
			}
			
			String result = MessageFormat.format(desc, list.toArray());
			
			map.put("result", result);
			map.put("checked", checked);
			map.put("rule", ruleText);
			
			results.add(map);
			
		}
		return results;
	}
	
	
	
	/**
	 * @param root
	 * @return
	 * 
	 * 条件
	 */
	public static List<Map<String,String>> parseCondition(Element root){
		
		List<Map<String,String>> options = new ArrayList<>();
		
		Element condition = root.element("condition");
		
		Iterator<?> i = condition.elementIterator("option");
		
		while(i.hasNext()){
			
			Map<String, String> map = new HashMap<>();
			
			Element option = (Element)i.next();
			
			String optionName = option.attributeValue("name");
			String checked = option.attributeValue("checked");
			String desc = option.elementText("desc");
			
			map.put("option", optionName);
			map.put("checked", checked);
			map.put("desc", desc);
			
			options.add(map);
		}
		
		return options;
		
	}
	
	/**
	 * @param root
	 * @return
	 * 
	 * 操作行为
	 * 
	 */
	public static List<Map<String,String>> parseBehavior(Element root){
		
		List<Map<String,String>> operations = new ArrayList<>();
		
		Element behavior = root.element("behavior");
		
		Iterator<?> i = behavior.elementIterator("operation");
		
		while(i.hasNext()){
			
			Map<String, String> map = new HashMap<>();
			
			Element operation = (Element)i.next();
			
			String operationName = operation.attributeValue("name");
			String checked = operation.attributeValue("checked");
			String desc = operation.elementText("desc");
			
			map.put("operation", operationName);
			map.put("checked", checked);
			map.put("desc", desc);
			
			operations.add(map);
		}
		
		return operations;
		
	}
	
	
	
	public static void updateInquiriesRule(MultiValueMap<String,Object> params) throws DocumentException, URISyntaxException, IOException{
		
		SAXReader reader = new SAXReader(); 
		Document document = reader.read(XMLUtil.class.getResource("/inquiries-rule.xml")); 
		Element root =  document.getRootElement();
		
		for(String key : params.keySet()){
			
			List<?> value = (List<?>)params.get(key);
			
			if(key.equals("rule")){
				Iterator<?> i = root.elementIterator("rule");
				while(i.hasNext()){
					Element rule = (Element)i.next();
					String rullName = rule.attributeValue("name");
					if(value.contains(rullName)){
						rule.attribute("checked").setValue("1");
					}else{
						rule.attribute("checked").setValue("0");
					}
				}
			}else if(key.equals("option")){
				Iterator<?> i = root.elementIterator("option");
				while(i.hasNext()){
					Element option = (Element)i.next();
					String optionName = option.attributeValue("name");
					if(value.contains(optionName)){
						option.attribute("checked").setValue("1");
					}else{
						option.attribute("checked").setValue("0");
					}
				}
			}else if(key.equals("operation")){
				Iterator<?> i = root.elementIterator("operation");
				while(i.hasNext()){
					Element operation = (Element)i.next();
					String operationName = operation.attributeValue("name");
					if(value.contains(operationName)){
						operation.attribute("checked").setValue("1");
					}else{
						operation.attribute("checked").setValue("0");
					}
				}
			}else{
				Node node = document.selectSingleNode("//value[@name='"+key+"']");
				if(value != null){
					if(value.size() > 0)
						node.setText(String.valueOf(value.get(0)));
				}
			}
			
		}
		
		OutputFormat format = OutputFormat.createPrettyPrint();
	    format.setEncoding("UTF-8"); // 给格式化输入器指定一个码表，xml文档什么编码，格式化输入器就是什么编码
	   
	    URL url = XMLUtil.class.getResource("/inquiries-rule.xml");
	    File file = new File(url.toURI());
	    FileOutputStream fos = new FileOutputStream(file);
	    XMLWriter writer = new XMLWriter(fos, format);
	    
	    writer.write(document);
	    writer.close();
		
	}
	

}
